/**
 * Created by think on 6/24/17.
 */
$(function() {
    var csrftoken = Cookies.get('csrftoken');
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });
    $("#subscribe").click(function(e){
        e.preventDefault();
        e.stopPropagation();
        if ($("#emailaddress")[0].checkValidity()){

            if ($("#emailtext")[0].checkValidity()) {
                if ($("#sendername")[0].checkValidity()) {
                    emailtext = $("#emailtext").val();
                    sendername = $("#sendername").val();
                    emailaddress = $("#emailaddress").val();
                    var data={ "emailaddress": emailaddress, "sendername":sendername, "emailtext":emailtext};
                    $.ajax("/email/", {
                        type: 'POST',
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify(data),
                        success: function (data) {
                           alert("留言已经收到！ 我们会尽快回复您.");
                           location.reload();
                        },
                        complete: function () {

                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            console.log(textStatus + ": " + errorThrown);
                        }
                    })
                        .done(function (data) {

                        });
                }
                else {alert("Invalid Name")}
            }
            else {alert("Invalid Email text")}
        }else{
            alert("Invalid Email Address");
        }
    });
});